package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCancelService;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderDeleteService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.*;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: cs-mall_35th
 * @description: 订单模块
 * @author: lmh
 **/
@RestController
@RequestMapping("/shopping")
public class OderController {
    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private OrderCoreService orderCoreService;

    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private OrderQueryService orderQueryService;

    @Reference(timeout = 3000, check = false)
    private OrderCancelService orderCancelService;

    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private ICartService iCartService;

    @Reference(timeout = 3000, check = false)
    private OrderDeleteService orderDeleteService;


    // 创建订单
    @PostMapping("/order")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) {

        // 1.处理请求参数：解析Json格式用户信息，拿到uid -- userId
        /*Long userInfo = (Long) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);

        request.setUserId(userInfo);*/
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("id").toString());

        request.setUserId(uid);


        //2.调用业务层
        CreateOrderResponse response = orderCoreService.createOrder(request);

        //3.返回数据
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            //清购物车缓存
            ClearCartItemRequest clearCartItemRequest = new ClearCartItemRequest();
            clearCartItemRequest.setUserId(uid);
            List<Long> arrayList = new ArrayList();
            List<CartProductDto> cartProductDtoList = request.getCartProductDtoList();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                arrayList.add(cartProductDto.getProductId());
            }
            clearCartItemRequest.setProductIds(arrayList);
            ClearCartItemResponse clearCartItemResponse = iCartService.clearCartItemByUserID(clearCartItemRequest);

            //成功  todo
            return new ResponseUtil<>().setData(response.getOrderId());
        }

        //失败
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    // 获取当前用户所有订单
    @GetMapping("/order")
    public ResponseData getOrdersByUserId(OrderListRequest request, HttpServletRequest httpServletRequest) {

        // 1.解析Json格式用户信息，拿到uid -- userId
        /*Long userInfo = (Long) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);

        request.setUserId(userInfo);*/

        String userInfo = (String) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("id").toString());

        request.setUserId(uid);



        OrderListResponse response = orderQueryService.getOrdersByUserId(request);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            // 封装结果集
            OrderListResult orderListResult = new OrderListResult();
            orderListResult.setData(response.getDetailInfoList());
            orderListResult.setTotal(response.getTotal());
            return new ResponseUtil().setData(orderListResult);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    // 查询订单详情
    @GetMapping("/order/{orderId}")
    public ResponseData getOrderById(@PathVariable("orderId") String orderId, HttpServletRequest httpServletRequest) {

        OrderDetailRequest request = new OrderDetailRequest();
        request.setOrderId(orderId);

        QueryOrderResponse response = orderQueryService.getOrderById(request);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getData());
        }

        return new ResponseUtil().setErrorMsg(response.getMsg());

    }


    // 取消订单
    @PostMapping("/cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {

        request.setOrderId(request.getOrderId());

        CancelOrderResponse response = orderCancelService.cancelOrder(request);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(SysRetCodeConstants.SUCCESS.getMessage());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    // 删除订单
    @DeleteMapping("/order/{orderId}")
    public ResponseData deleteOrder(@PathVariable("orderId") Long orderId) {

        DeleteOrderRequest request = new DeleteOrderRequest();
        request.setOrderId(orderId.toString());

        DeleteOrderResponse deleteOrder = orderDeleteService.deleteOrder(request);
        if (deleteOrder.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(OrderRetCode.SUCCESS.getMessage());
        }

        return new ResponseUtil<>().setErrorMsg(deleteOrder.getMsg());

    }



}
